package com.ytktt.study.week9.task3.rpcfx.server.netty.coder;

import com.ytktt.study.week9.task3.rpcfx.utils.ProtoStuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * protostff netty解码器
 *
 * @author ytk
 */
@RequiredArgsConstructor
public class ProtostuffDecoder extends ByteToMessageDecoder {

    private final Class<?> returnType;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//        byte[] data = new byte[in.readableBytes()];
//        in.readBytes(data);
//        out.add(ProtoStuffUtil.deserialize(data, this.returnType));

        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        out.add(ProtoStuffUtil.deserialize(data, this.returnType));
    }
}
